package com.kun.example.rpc;

import com.kun.example.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author 小K
 * @date 2022/4/9 0009 - 下午 15:53
 */
public class RpcNetTransport {

    private String host;

    private int port;

    public RpcNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Socket newSocket() throws IOException {

        Socket socket = new Socket(host, port);
        return socket;
    }

    public Object send(RpcRequest request){

        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;

        try {
            Socket socket = newSocket();
            //IO
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();
            inputStream = new ObjectInputStream(socket.getInputStream());
            return inputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
